// internal/repositories/user_repository.go
package repositories

import (
	"mygin/internal/models"

	"gorm.io/gorm"
)

type UserRepository struct {
	db *gorm.DB
}

func NewUserRepository(db *gorm.DB) *UserRepository {
	return &UserRepository{db: db}
}

// 所有CRUD方法
func (r *UserRepository) Create(user *models.User) error {
	return r.db.Create(user).Error
}

func (r *UserRepository) GetByID(id uint) (*models.User, error) {
	var user models.User
	err := r.db.First(&user, id).Error
	return &user, err
}

// UserFilter 筛选条件
type UserFilter struct {
	Username string
	Email    string
}

// ListWithPagination 获取列表（带分页）
func (r *UserRepository) ListWithPagination(page, pageSize int, filter UserFilter) ([]models.User, int64, error) {
	var users []models.User
	var total int64

	query := r.db.Model(&models.User{})

	// 应用筛选条件
	if filter.Username != "" {
		query = query.Where("username LIKE ?", "%"+filter.Username+"%")
	}
	if filter.Email != "" {
		query = query.Where("email LIKE ?", "%"+filter.Email+"%")
	}

	// 计算总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * pageSize
	if err := query.Offset(offset).Limit(pageSize).Find(&users).Error; err != nil {
		return nil, 0, err
	}

	return users, total, nil
}

// 更新
func (r *UserRepository) Update(user *models.User) error {
	// 使用Select指定只更新非零值字段
	return r.db.Model(user).
		Select("*").
		Where("id = ?", user.ID).
		Updates(user).Error
}

func (r *UserRepository) UpdatePartial(id uint, data map[string]interface{}) error {
	return r.db.Model(&models.User{}).Where("id = ?", id).Updates(data).Error
}

// 软删除
func (r *UserRepository) DeleteByID(id uint) error {
	// 使用Delete实现软删除（需要模型中有gorm.DeletedAt字段）
	return r.db.Delete(&models.User{}, id).Error
}

// 硬删除
func (r *UserRepository) HardDeleteByID(id uint) error {
	// 使用Unscoped().Delete实现硬删除
	return r.db.Unscoped().Delete(&models.User{}, id).Error
}

// 其他方法：Update/Delete/GetAll等...

/****************非curd方法区**************************/
func (r *UserRepository) FindByUsername(username string) (*models.User, error) {
	var user models.User
	if err := r.db.Where("username = ?", username).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

func (r *UserRepository) GetUserWithOrders(userID uint) (map[string]interface{}, error) {
	var result map[string]interface{}
	err := r.db.Raw(`
        SELECT u.id, u.username, o.id as order_id, o.order_sn 
        FROM users u
        JOIN `+"`order`"+` o ON u.id = o.user_id
        WHERE u.id = ?
    `, userID).Scan(&result).Error
	r.db = r.db.Debug() // 显示实际执行的SQL
	return result, err
}
